package impl.myjdkimpl;

import utils.io.FileUtils;

import java.io.File;

/**
 * Created by chenjun on 2017/11/21.
 */
public class MyClassLoader extends  ClassLoader {

    private File classFileDir;

    public MyClassLoader(String filename) {
        this.classFileDir = new File(filename);
    }

    public MyClassLoader(){
        String currentDir = MyClassLoader.class.getProtectionDomain().getCodeSource().getLocation().getPath();

        this.classFileDir = new File(currentDir);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        File classFile = new File(this.classFileDir, name + ".class");
        if(classFile.exists()) {
                byte[] classData = FileUtils.copyToByteArray(classFile);
                return defineClass(name, classData, 0, classData.length);
        }

        return super.findClass(name);
    }
}
